package com.jinyijia.api.rest.v1.shippingaddress;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinyijia.api.infrastructure.UserInfoManager;
import com.jinyijia.api.rest.v1.shippingaddress.dto.ReceivingInformationDTO;
import com.jinyijia.api.rest.v1.shippingaddress.dto.ShippingAddressDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author yangrd
 * @date 2018/8/8
 * 接口7收货地
 **/
@RestController
@RequestMapping("shipping-address")
public class ShippingAddressController {

    private RestTemplate restTemplate;

    @Autowired
    public ShippingAddressController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping
    public Result<ShippingAddress> list() {
        Integer currentUserId = UserInfoManager.getCurrentUserId();
        JSONArray jsonArray = restTemplate.getForObject("http://user-service/users/receivingInformation/" + currentUserId, JSONArray.class);
        List<ShippingAddress> list = new ArrayList<>();
        jsonArray.forEach(o -> {
            JSONObject jsonObject = new JSONObject((Map<String, Object>) o);
            list.add(map(jsonObject));
        });
        return new Result<>(list);
    }

    private ShippingAddress map(JSONObject jsonObject) {
        return new ShippingAddress(
                jsonObject.getInteger("id"),
                jsonObject.getString("name"),
                jsonObject.getBoolean("enabled"),
                jsonObject.getString("mobile"),
                jsonObject.getString("province") + jsonObject.getString("city") + jsonObject.getString("district") + jsonObject.getString("town"),
                jsonObject.getString("road")
        );
    }

    /**
     * 添加用户收货地址
     *
     * @param shippingAddressDTO
     * @return
     * @author WX
     * @date 2018/8/15
     */
    @PostMapping
    public ResponseEntity addShippingAddress(@RequestBody ShippingAddressDTO shippingAddressDTO) {
        Integer userId = UserInfoManager.getCurrentUserId();
        String url = "http://user-service/users/receivingInformation/";
        ReceivingInformationDTO receivingInformationDTO = new ReceivingInformationDTO(shippingAddressDTO);
        receivingInformationDTO.setUserId(userId);
        try {
            restTemplate.postForEntity(url, receivingInformationDTO, Object.class);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(false);
        }
        return ResponseEntity.ok(true);
    }

    /**
     * 修改用户收货地址(h5页面需要)
     *
     * @param shippingAddressDTO
     * @return
     * @author WX
     * @date 2018/10/9
     */
    @PostMapping("/{id}")
    public ResponseEntity updataShippingAddress(@PathVariable Integer id, @RequestBody ShippingAddressDTO shippingAddressDTO) {
        Integer userId = UserInfoManager.getCurrentUserId();
        String url = "http://user-service/users/receivingInformation/{1}";
        ReceivingInformationDTO receivingInformationDTO = new ReceivingInformationDTO(shippingAddressDTO);
        receivingInformationDTO.setUserId(userId);
        try {
            restTemplate.postForEntity(url, receivingInformationDTO, Object.class, id);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.ok(false);
        }
        return ResponseEntity.ok(true);
    }

    /**
     * 删除当前用户的收货地址
     *
     * @param id
     * @author WX
     * @date 2018/8/15
     */
    @DeleteMapping("/{id}")
    public ResponseEntity deleteShippingAddress(@PathVariable("id") Integer id) {
        try {
            restTemplate.delete("http://user-service/users/receivingInformation/{1}", id);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(false);
        }
        return ResponseEntity.ok(true);
    }

    /**
     * 修改收货地址
     *
     * @param id
     * @return
     * @author WX
     * @date 2018/8/15
     */
    @PutMapping("/{id}")
    public ResponseEntity updateShippingAddress(@PathVariable("id") Integer id) {
        try {
            restTemplate.put("http://user-service/users/receivingInformation/{1}", null, id);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(false);
        }
        return ResponseEntity.ok(true);
    }

    /**
     * 查询当前用户已启用的收货地址
     *
     * @return
     */
    @GetMapping("/enabled")
    public ShippingAddress getShippingAddress() {
        Integer currentUserId = UserInfoManager.getCurrentUserId();
        JSONObject jsonObject = restTemplate.getForObject("http://user-service/users/receivingInformation/{1}/enabled", JSONObject.class, currentUserId);
        if (Objects.nonNull(jsonObject)) {
            return new ShippingAddress(
                    jsonObject.getInteger("id"),
                    jsonObject.getString("name"),
                    jsonObject.getBoolean("enabled"),
                    jsonObject.getString("mobile"),
                    jsonObject.getString("province") + "-" + jsonObject.getString("city") + "-" + jsonObject.getString("district"),
                    jsonObject.getString("road")
            );
        } else {
            return new ShippingAddress();
        }

    }

    /**
     * 查询当前用户要编辑的收货地址详情
     *
     * @return
     */
    @GetMapping("/{id}")
    public ShippingAddress getShippingAddressDetail(@PathVariable("id") Integer id) {
        JSONObject jsonObject = restTemplate.getForObject("http://user-service/users/receivingInformation/{1}/detail", JSONObject.class, id);
        if (Objects.nonNull(jsonObject)) {
            return new ShippingAddress(
                    jsonObject.getInteger("id"),
                    jsonObject.getString("name"),
                    jsonObject.getBoolean("enabled"),
                    jsonObject.getString("mobile"),
                    jsonObject.getString("province") + "-" + jsonObject.getString("city") + "-" + jsonObject.getString("district"),
                    jsonObject.getString("road")
            );
        } else {
            return new ShippingAddress();
        }

    }
}
